package com.bmob.lover.viewmodel

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.bmob.lover.app.ext.getVideoThumbnail
import com.bmob.lover.data.model.bean.*
import com.bmob.lover.data.repository.BmobRepository
import com.luck.picture.lib.config.SelectMimeType
import com.theone.mvvm.core.app.ext.msg
import com.theone.mvvm.core.base.viewmodel.BaseRequestViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-30 10:37
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class UploadFileViewModel : BaseRequestViewModel<List<TheFile>>() {

    private val mUploadList: MutableList<TheFile> = mutableListOf()
    private val mUploadPaths: MutableList<String> = mutableListOf()
    private val mUploadFileNames: MutableList<String> = mutableListOf()
    private var mTotalSize: Long = 0L
    private val suffix = "thumbnail_"
    private var uploadSize: Long = 0L

    override fun requestServer() {
        viewModelScope.launch {
            showProgressDialog("上传中")
            // 请求开始
            for (index in 0 until mUploadPaths.size) {
                BmobRepository.INSTANCE.uploadFile(mUploadFileNames[index], mUploadPaths[index]) {
                    val curSize = uploadSize + it.currentSize
                    if (it.progress == 100) {
                        uploadSize += it.totalSize
                    }
                    showProgressDialog("上传中", curSize.toInt(), mTotalSize.toInt())
                }.catch {
                    // 错误回调
                    onError(it.msg)
                    hideProgressDialog()
                }.collect {
                    // 将上传好的图片地址填充到即将保存的数据里
                    for (file in mUploadList) {
                        // 判断是原图还是缩略图
                        when (it.filename) {
                            file.mFileName -> {
                                file.path = it.url
                                break
                            }
                            file.getUploadThumbnailName() -> {
                                file.mThumbnail = it.url
                                break
                            }
                            else -> {
                                continue
                            }
                        }
                    }
                }
            }
            onSuccess(mUploadList)
            // 请求结束
            onFinally()
        }
    }

    fun uploadFiles(selects: List<LocalMedia>) {
        showProgressDialog("准备中")
        mUploadList.clear()
        for (media in selects) {
            val type = PictureMimeType.getMimeType(media.mimeType)
            val file = TheFile()
            file.type = type
            file.mWidth = media.width
            file.mHeight = media.height
            file.mFileName = media.fileName
            file.mSize = media.size
            file.localPath = media.path
            val isVideo = type == SelectMimeType.TYPE_VIDEO
            //视频只让选一个
            if (isVideo) {
                file.mThumbnail =
                    getVideoThumbnail(file.localPath)
            } else if (media.isCompressed && media.compressPath != file.localPath) {
                file.mThumbnail = media.compressPath
            }
            mUploadList.add(file)
        }
        setUploadFilePaths()
        requestServer()
    }

    private fun setUploadFilePaths() {
        mUploadPaths.clear()
        mUploadFileNames.clear()
        for (file in mUploadList) {
            with(file) {
                // 原始图片
                mUploadPaths.add(localPath)
                mUploadFileNames.add(mFileName)
                mTotalSize += file.mSize
                // 如果存在缩略图，就添加上
                if (!TextUtils.isEmpty(mThumbnail)) {
                    mTotalSize += File(mThumbnail).length()
                    mUploadPaths.add(mThumbnail)
                    // 名称添加缩略图备注
                    mUploadFileNames.add(getUploadThumbnailName())
                }
            }
        }
    }

    private fun TheFile.getUploadThumbnailName(): String {
        return suffix + File(mThumbnail).name
    }
}
